<template>
  <el-tree
    ref="treeRef"
    :data="treeData"
    node-key="projectId"
    :props="defaultProps"
    :expand-on-click-node="false"
    :draggable="isbtnshow"
    highlight-current
    :allow-drop="allowDrop"
    :default-expanded-keys="[props.projectIdShow]"
    :indent="20"
    @node-click="handleNodeClick"
    @node-drop="handleDrop"
    class="custom-tree"
  >
    <template #default="{ node, data }">
      <div class="tree-node-content">
        <span v-if="!data.isEditing" class="node-name">{{ node.label }}</span>
        <el-input
          v-else
          v-model="data.editName"
          size="small"
          @blur="saveEdit(data)"
          @keyup.enter="saveEdit(data)"
          @keyup.escape="cancelEdit(data)"
          ref="nameInput"
          class="edit-input"
        />

        <div class="node-actions" v-if="isbtnshow">
          <el-button type="primary" size="small" @click.stop="addChild(node, data)" plain>
            <el-icon><Plus /></el-icon>
          </el-button>
          <el-button type="warning" size="small" @click.stop="startEdit(data)" plain>
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button type="danger" size="small" @click.stop="removeNode(node, data)" plain>
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </template>
  </el-tree>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import { ElMessageBox, ElMessage, ElTree } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

export interface TreeNode {
  projectId: string | number;
  projectName: string;
  sort?: number;
  childrens?: TreeNode[];
}

const props = defineProps<{
  node: TreeNode[];
  isbtnshow?: boolean;
  projectIdShow
}>();

const emit = defineEmits<{
  (e: "add-node", parentId: string | number, name: string): void;
  (e: "edit-node", id: string | number, name: string,parentId?:string): void;
  (e: "remove-node", id: string | number): void;
  (e: "click-node", id: string | number): void;
  (
    e: "drag-node",
    draggedId: string | number,
    targetId: string | number,
    dropPosition: "before" | "after" | "inner"
  ): void;
}>();

const treeRef = ref<InstanceType<typeof ElTree>>();
const defaultProps = {
  children: "childrens",
  label: "projectName",
};


// 将原始数据转换为el-tree需要的数据格式
const treeData = ref(props.node)
// const treeData = computed(() => {
//   return [{
//     ...props.node,
//     isEditing: false,
//     editName: ""
//   }];
// });

const handleNodeClick = (data: TreeNode) => {
  // 点击节点逻辑
    emit("click-node", data.projectId);
};

const startEdit = (data: any) => {
  data.isEditing = true;
  data.editName = data.projectName;
  nextTick(() => {
    // 这里需要获取到具体的input元素进行focus
    const input = document.querySelector('.edit-input input') as HTMLInputElement;
    input?.focus();
  });
};

const saveEdit = (data: any) => {
  if (data.editName.trim()) {
    emit("edit-node", data.projectId, data.editName);
    data.isEditing = false;
  }
};

const cancelEdit = (data: any) => {
  data.isEditing = false;
};

const addChild = (node: any, data: TreeNode) => {
  ElMessageBox.prompt("请输入子项名称", "添加子节点", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /.+/,
    inputErrorMessage: "名称不能为空",
  })
    .then(({ value }) => {
      emit("add-node", data.projectId, value);
      if (!node.expanded) {
        node.expand();
      }
    })
    .catch(() => {});
};

const removeNode = (node: any, data: TreeNode) => {
  ElMessageBox.confirm(
    `确定要删除 "${data.projectName}" 吗?`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      emit("remove-node", data.projectId);
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

// 拖拽相关
const allowDrop = (draggingNode: any, dropNode: any, type: 'prev' | 'inner' | 'next') => {
  // 这里可以添加自定义的拖拽限制逻辑
  return props.isbtnshow;
};

const handleDrop = (draggingNode: any, dropNode: any, dropType: 'before' | 'after' | 'inner') => {
  const draggedId = draggingNode.data.projectId;
  const targetId = dropNode.data.projectId;
  
  // 将el-tree的dropType转换为我们的类型
  let position: "before" | "after" | "inner";
  if (dropType === 'before') position = 'before';
  else if (dropType === 'after') position = 'after';
  else position = 'inner';
  
  emit("drag-node", draggedId, targetId, position);
};
</script>

<style scoped lang="scss">
.custom-tree {
  :deep(.el-tree-node) {
    position: relative;
    // padding-left: 20px;
    
    &::before {
      content: '';
      position: absolute;
      left: 10px;
      top: 0;
      bottom: 0;
      border-left: 1px dashed var(--el-border-color);
    }
    
    &:last-child::before {
      height: 20px;
    }
  }

  :deep(.el-tree-node__content) {
    height: auto;
    padding: 5px 0;
    margin-left: 10px;
    
    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }

  .tree-node-content {
    display: flex;
    align-items: center;
    padding: 8px;
    border-radius: 4px;
    transition: all 0.3s;
    cursor: pointer;
    width: 100%;
    margin-left: 10px;
    justify-content: space-between;

    .node-name {
      flex: 1;
      margin-right: 10px;
      font-size: 14px;
    }

    .edit-input {
      flex: 1;
      margin-right: 10px;
    }

    .node-actions {
      display: flex;
      gap: 5px;

      .el-button {
        padding: 5px 8px;
      }
    }
  }

  :deep(.el-tree-node__expand-icon) {
    color: var(--el-color-primary);
    font-size: 14px;
    margin-right: 8px;
    
    &.is-leaf {
      color: var(--el-color-primary);
    }
  }
}
</style>